<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="只允许为第三级设置相关参数" type="warning" show-icon :closable="false"></el-alert>
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectParamsKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab；栏部分 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态属性" name="many">
          <!-- 添加参数按钮 -->
          <el-button :disabled="isBtnDisabled" type="primary" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 添加动态参数表格区域 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <el-table-column align="center" type="expand">
              <template slot-scope="scope">
                <!-- {{ scope.row}} -->
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteParams(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="medium"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" type="index" label="#"></el-table-column>
            <el-table-column align="center" prop="attr_name" label="动态参数"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  plain
                  type="success"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  plain
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button :disabled="isBtnDisabled" type="primary" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 添加静态参数表格区域 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <el-table-column align="center" type="expand">
              <template slot-scope="scope">
                <!-- {{ scope.row}} -->
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                >{{item}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" type="index" label="#"></el-table-column>
            <el-table-column align="center" prop="attr_name" label="静态参数"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  plain
                  type="success"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  plain
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加区域对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addParamsFormClear"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editParamsFormClear"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 定义接收数据的数组
      cateList: [],

      // 定义级联选择器的相关参数
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },

      // 定义级联选择器所选择的数组
      selectParamsKeys: [],

      // 定义tab栏的默认显示
      activeName: 'many',

      // 获得添加动态参数的表格绑定数据数组
      manyTableData: [],

      // 获取静态参数的表格绑定的数组
      onlyTableData: [],

      // 定义添加属性对话框的显示和隐藏
      addDialogVisible: false,

      // 添加表单的数据对象
      addParamsForm: {
        attr_name: ''
      },

      // 添加验证规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // 编辑数据
      editParamsForm: {},

      // 对话框的默认显示
      editDialogVisible: false,

      // 编辑验证规则
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // inputVisible 控制输入框的现实和隐藏
      inputVisible: false,

      // inputValue双向绑定的值
      inputValue: ''
    }
  },
  created () {
    this.getCateLsit()
  },

  methods: {
    // 定义获取参数分类的数据的方法
    async getCateLsit () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      // console.log(this.cateList)
    },

    // 定义级联选择鼠标触发时候的事件 获取表格数据
    async getParamsData () {
      // console.log(this.selectParamsKeys)
      // 先判断是否为第三级参数 不是就返回空的数组 是就可以获取数据
      if (this.selectParamsKeys.length !== 3) {
        this.selectParamsKeys = []
        return
      }
      // 获取表格绑定的数据 根据分类id获取
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      // 在这里将res.data遍历 然后attr_vals字符串转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 定义级联选择鼠标触发时候的事件 获取表格数据
    handleChange () {
      this.getParamsData()
    },

    // 鼠标点击tab栏切换
    handleClick () {
      // this.activeName = 'only'
      this.getParamsData()
    },

    // 关闭对话框 清空表单
    addParamsFormClear () {
      this.$refs.addParamsFormRef.resetFields()
    },

    // 点击确定 验证后发送请求
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        // console.log(valid)
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.addDialogVisible = false
      })
    },

    // 点击编辑  // 根据id先来查询数据 并渲染到页面
    async editParams (attrId) {
      // console.log(attrId)
      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes/${attrId}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParamsForm = res.data
      // console.log(res.data)
      this.editDialogVisible = true
    },

    // 点击确定提交
    editParamsCate () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.editParamsForm.attr_sel
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },

    // 清空表单验证
    editParamsFormClear () {
      this.$refs.editParamsFormRef.resetFields()
    },

    // 删除参数
    async removeParams (attrId) {
      // console.log(attrId)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('您取消删除')
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },

    // 抽取公共部分
    async saveArrts (row) {
      const { data: res } = await this.$http.put(`/categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      // console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },

    // 点击和enter控制输入框都会触发
    async handleInputConfirm (row) {
      // console.log('ok')
      // 如果文本框的长度为0就返回数组和数据为
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return 证明通过后先将数据传导数组中 清空表单后发送编辑参数请求
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveArrts(row)
    },

    // 控制输入框的显示和隐藏
    showInput (row) {
      row.inputVisible = true
      // 鼠标点击输入框自动获得聚焦效果
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 点击叉号删除
    deleteParams (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveArrts(row)
    }
  },
  computed: {
    // 定义一个按钮的禁用开启属性 只有当参数为第三级事才能添加
    isBtnDisabled () {
      if (this.selectParamsKeys.length === 3) {
        return false
      } else {
        return true
      }
    },

    // 获得分类cateId
    cateId () {
      if (this.selectParamsKeys.length === 3) {
        return this.selectParamsKeys[2]
      } else {
        return null
      }
    },

    // 定义对话框标题切换的计算
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat-opt {
  margin: 15px 0;

  .el-cascader {
    margin-left: 10px;
  }
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 125px;
}
</style>
